package org.alesv.entranceExams.dao.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.alesv.common.collection.Trie;
import org.alesv.common.logging.annotations.LogDebug;
import org.alesv.entranceExams.Config;
import org.alesv.entranceExams.dao.WordsDictionaryDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * *
 * 
 * @author asantamaria
 */
@Repository
public class WordsDictionaryDaoImpl implements WordsDictionaryDao {

	/**
	 * To log
	 */
	private final Logger log = LoggerFactory
			.getLogger(WordsDictionaryDaoImpl.class);

	/**
	 * Acceso al fichero de configuración de la aplicación.
	 */
	@Autowired
	private Config config;

	private Trie wordsDictionary;

	@LogDebug(loggerClass = WordsDictionaryDaoImpl.class)
	public Trie getWordsDictionary() {
		if (wordsDictionary == null) {
			log.debug("wordsDictionary is null. Let's load it.");

			wordsDictionary = new Trie();

			try {
				BufferedReader in = new BufferedReader(new InputStreamReader(
						getClass().getClassLoader().getResourceAsStream(
								"word.lst")));

				String userInput;

				while ((userInput = in.readLine()) != null) {
					wordsDictionary.insert(userInput);
				}

				log.debug("wordsDictionary loaded");
			} catch (IOException e) {
				log.error("Error loading wordsDictionary");
			}
		}
		return wordsDictionary;
	}

	@LogDebug(loggerClass = WordsDictionaryDaoImpl.class)
	public boolean existWordWithPrefix(String prefix) {
		return (indexOfPrefix(prefix) != -1);
	}

	@LogDebug(loggerClass = WordsDictionaryDaoImpl.class)
	public int indexOfPrefix(String prefix) {
		return indexOfPrefix(prefix, 0);
	}

	@LogDebug(loggerClass = WordsDictionaryDaoImpl.class)
	public int indexOfPrefix(String prefix, int from) {
		int result = -1;

		return result;
	}

	@LogDebug(loggerClass = WordsDictionaryDaoImpl.class)
	public boolean existWord(String word) {
		return getWordsDictionary().search(word);
	}

}
